package com.strongbj.iot.devices.dam.sub.dacai.response.handle;

import java.io.UnsupportedEncodingException;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.iot.devices.dam.common.AbstractTaskDelayedRunnable;
import com.strongbj.iot.devices.dam.common.DAMManager;
import com.strongbj.iot.devices.dam.common.ITaskManager;
import com.strongbj.iot.devices.dam.message.DAMMessage;
import com.strongbj.iot.devices.dam.message.DAMMessageFactory;
import com.strongbj.iot.devices.dam.sub.dacai.entity.DaCaiBindRFIDMenuManager;
import com.strongbj.iot.devices.dam.sub.dacai.entity.DaCaiBindRFIDMenuManager.MenuContext;
import com.strongbj.iot.devices.dam.sub.dacai.entity.DaCaiBindRFIDMenuManager.MenuItem;
import com.strongbj.iot.devices.dam.sub.dacai.message.DaCaiMessage;
import com.strongbj.iot.devices.dam.sub.dacai.message.DaCaiMessageType;
import com.strongbj.iot.devices.dam.sub.dacai.response.entity.ScreenReturnEntity;
import com.strongbj.iot.devices.dam.sub.dacai.response.entity.ScreenReturnFactory;
import com.strongbj.iot.devices.dam.sub.dacai.response.entity.ScreenReturnTableControlEntity;
import com.strongbj.iot.devices.dam.sub.dacai.response.entity.ScreenReturnTableControlFactory;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;

/**
 * 选择绑定RFID的菜单选项
 * 
 * @author yuzhantao
 *
 */
public class SelectBindRFIDMenuItemHandle implements IMessageHandle<DaCaiMessage, Object> {
	private static Logger logger = LogManager.getLogger(SelectBindRFIDMenuItemHandle.class.getName());
	protected final static String BUTTON_COMMAND_CODE = "B111"; // 打开页面命令的编号
	protected final static String TABLE_COMMAND_CODE = "B15A"; // 打开页面命令的编号
	protected final static byte TO_SCREEN_COMMAN = (byte) 0xFF; // 获取传感器参数
//	protected final static String NET_PAGE_INDEX = "0004";  	// 网络设置页面的索引
	protected final static String DEFAULT_DEVICE_CODE = "000000"; // 设备默认编号
	protected DAMMessageFactory damMessageFactory = new DAMMessageFactory();

	private short openSelectAssetListMenuByControlId = -1; // 打开选择资产列表的控件ID

	protected DAMMessage currentDAM;

	public SelectBindRFIDMenuItemHandle(DAMMessage dam) {
		this.currentDAM = dam;
	}

	@Override
	public boolean isHandle(DaCaiMessage t) {
		if (t.getMessageType() == DaCaiMessageType.System) {
			ScreenReturnEntity sr = ScreenReturnFactory.create(t.getDatas());
			if (t.getCommand().equals(BUTTON_COMMAND_CODE)) {
				// 如果点击触发的控件类型为按钮，屏幕id为11，按钮id为2，就认为是打开传感器设置界面
				if (sr.getControlType() == 16 && sr.getScreenId() == 11 && sr.getControlId() == 2)
					return true;
				// 如果点击触发的控件类型为按钮，屏幕id为10，按钮id为601~622，就认为是打开选择资产菜单界面
				if (sr.getControlType() == 16 && sr.getScreenId() == 10
						&& (sr.getControlId() > 600 && sr.getControlId() < 623))
					return true;
			} else if (t.getCommand().equals(TABLE_COMMAND_CODE)) {
				// 如果点击触发的控件类型为表格，屏幕id为11，按钮id为1，就认为是选择
				if (sr.getControlType() == 29 && sr.getScreenId() == 11 && sr.getControlId() == 1)
					return true;
			}
		}
		return false;
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, DaCaiMessage t) {
		MenuContext menu = DaCaiBindRFIDMenuManager.getInstance()
				.getMenu(ByteUtil.byteArrToHexString(this.currentDAM.getAddressCode()));
		if (menu == null)
			return null;

		// 如果点击了表格中的选项
		if (t.getCommand().equals(TABLE_COMMAND_CODE)) {
			ScreenReturnTableControlEntity sr = ScreenReturnTableControlFactory.create(t.getDatas());
			menu.setSelectIndex(sr.getSelectIndex());
			return null;
		}

		ScreenReturnEntity sr = ScreenReturnFactory.create(t.getDatas());
		if (t.getCommand().equals(BUTTON_COMMAND_CODE) && sr.getScreenId() == 10) {
			openSelectAssetListMenuByControlId = sr.getControlId();
			return null;
		}

		// 如果选项不正常，就不设置
		if (menu.getSelectIndex() < 0 || menu.getSelectIndex() > menu.getMenuItemList().size() - 1)
			return null;
		// 如果不知道哪个按钮打开了菜单，也不设置
		if (this.openSelectAssetListMenuByControlId < 0)
			return null;

		Channel channel = ctx.channel();
		ITaskManager taskManager = DAMManager.getTaskManager(t.getDamCode());
		taskManager.addSendTask(new AbstractTaskDelayedRunnable() {
			@Override
			protected void taskRun() {
				if (channel != null && channel.isActive()) {
					try {
						// 发送获取DAM传感器参数的命令到DAM
						sendSetSelectAssetParamsMessage(channel, menu);
					} catch (UnsupportedEncodingException e1) {
						e1.printStackTrace();
					}
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				} else {
					logger.error("主机没有找到指定channel");
				}
			}
		});

		return null;
	}

	/**
	 * 发送获取本地网络的消息
	 * 
	 * @param channel
	 * @throws UnsupportedEncodingException
	 */
	private void sendSetSelectAssetParamsMessage(Channel channel, MenuContext menu)
			throws UnsupportedEncodingException {
		short id = (short) ((this.openSelectAssetListMenuByControlId - 601) * 5 + 1);
		// 整个在屏幕第10个界面显示选择的资产信息命令
		MenuItem menuItem = menu.getMenuItemList().get(menu.getSelectIndex());
		StringBuffer sb = new StringBuffer("EEB112000A");

		sb.append(ByteUtil.byteArrToHexString(ByteUtil.shortToByteArr(id)));
		String hexAssetId = ByteUtil.byteArrToHexString(menuItem.getAssetId().getBytes("GBK"));
		sb.append(ByteUtil.byteArrToHexString(ByteUtil.shortToByteArr((short) (hexAssetId.length() / 2))));
		sb.append(hexAssetId);

		sb.append(ByteUtil.byteArrToHexString(ByteUtil.shortToByteArr((short) (id + 2))));
		String hexAssetName = ByteUtil.byteArrToHexString(menuItem.getAssetName().getBytes("GBK"));
		sb.append(ByteUtil.byteArrToHexString(ByteUtil.shortToByteArr((short) (hexAssetName.length() / 2))));
		sb.append(hexAssetName);

		sb.append("FFFCFFFF");
		// 将命令下发到屏幕
		final byte[] datas = message2Bytes(DEFAULT_DEVICE_CODE, TO_SCREEN_COMMAN, sb.toString());
		sb.setLength(0); // 释放sb中的内存

		ByteBuf bs = Unpooled.copiedBuffer(datas);
		ChannelFuture cf = channel.writeAndFlush(bs);
		cf.addListener(new ChannelFutureListener() {

			@Override
			public void operationComplete(ChannelFuture future) throws Exception {
				if (future.isSuccess()) {
					logger.info("DAM自动下发设置选择绑定RFID的资产命令成功 下发命令={}  ", ByteUtil.byteArrToHexString(datas, true));
				} else {
					logger.error("DAM自动下发设置选择绑定RFID的资产命令失败 下发命令={}  ", ByteUtil.byteArrToHexString(datas, true));
				}
			}
		});
	}

	/**
	 * 获取传感器命令转byte数组
	 * 
	 * @param np
	 * @return
	 */
	private byte[] message2Bytes(String deviceCode, byte command, String datas) {
		// 创建设置目标服务器的指令
		byte[] retDatas = damMessageFactory.createDAMMessage(ByteUtil.longToBytes(System.currentTimeMillis()),
				deviceCode, // 设备编号
				(byte) 0, // 设备类型，默认填0
				(byte) 0, // 版本号，默认填0
				command, // 命令
				ByteUtil.hexStringToBytes(datas) // 空参数
		); // 通过dam消息工厂获取指令
		return retDatas;
	}
}
